﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace DigitMatrix.Business
{
    class GeneratorFileInfo
    {
        //generate video file name
        public const int DEFFFILEMIN = 1;
        public static Dictionary<string, DateTime> SearchVideoFileName(string baseOutpputPath, string extFile, int camercaId, DateTime dStartTime, DateTime dEndDate)
        {

            if (baseOutpputPath.Substring(baseOutpputPath.Length - 1, 1).Equals("\\"))
            {
                baseOutpputPath = baseOutpputPath.Substring(0, baseOutpputPath.Length - 1);
            }
            string startPath = string.Format("{0}\\{1}\\{2}{3}{4}\\{5}\\",
                                baseOutpputPath,
                                camercaId,
                                dStartTime.Year.ToString("d4"),
                                dStartTime.Month.ToString("d2"),
                                dStartTime.Day.ToString("d2"),
                                dStartTime.Hour.ToString("d2")
                                );
            string endPath = string.Format("{0}\\{1}\\{2}{3}{4}\\{5}\\",
                            baseOutpputPath,
                            camercaId,
                            dEndDate.Year.ToString("d4"),
                            dEndDate.Month.ToString("d2"),
                            dEndDate.Day.ToString("d2"),
                            dEndDate.Hour.ToString("d2")
                            );
            var d = new Dictionary<string, DateTime>();
            FileInfo oFileInfo;
            DateTime dt;
            string[] files;
            string[] splitStr;
            string fileDirect;
            string strFile = "";
            string strFileMin = "";
            int iFileMin = 0;
            DateTime dtFileSaveTime;
            dStartTime = dStartTime.AddMinutes(-1 * Config.DEFFFILEMIN);
            int hours = (int)dEndDate.Subtract(dStartTime).TotalHours;
            for (int j = 0; j <= hours; j++)
            {
                dt = dStartTime.AddHours(j);
                fileDirect = GeneratorFileInfo.GenerateSavePath(baseOutpputPath, camercaId, dt);
                files = Directory.GetFiles(fileDirect, "*." + extFile);
                for (int i = 0; i < files.Length; i++)
                {
                    FileInfo fi = new FileInfo(files[i]);
                   // if ((fi.CreationTime.CompareTo(dStartTime) >= 0 && fi.LastWriteTime.CompareTo(dEndDate) <= 0) )//|| (fi.CreationTime.CompareTo(dEndDate) >= 0 && fi.LastWriteTime.CompareTo(dEndDate) <= 0))
                    if (fi.CreationTime.CompareTo(dStartTime) >= 0 && fi.LastWriteTime.CompareTo(dEndDate)<=0)//|| (fi.CreationTime.CompareTo(dEndDate) >= 0 && fi.LastWriteTime.CompareTo(dEndDate) <= 0))
                    {
                        if (!d.ContainsKey(files[i]))
                        {
                            d.Add(files[i], new FileInfo(files[i]).CreationTime);
                        }
                    }


                    //splitStr = files[i].Split('\\');
                    //strFile = splitStr[splitStr.Length - 1];
                    //splitStr = strFile.Split('.');
                    //if (!int.TryParse(splitStr[0], out iFileMin))
                    //{
                    //    continue;
                    //}
                    //if (iFileMin < 0 || iFileMin >= 60)
                    //{
                    //    continue;
                    //}
                    //strFileMin = iFileMin.ToString("99");
                    //dtFileSaveTime = DateTime.Parse(dt.ToString("yyyy/MM/dd HH:mm").Substring(0, 14) + strFileMin + ":00");
                    //if (dtFileSaveTime.CompareTo(dStartTime) > 0 && dtFileSaveTime.CompareTo(dEndDate) <= 0)
                    //{
                    //    if (!d.ContainsKey(files[i]))
                    //    {
                    //        d.Add(files[i], new FileInfo(files[i]).LastWriteTime);
                    //    }
                    //}

                }

            }

            return d;
        }
        public static string GetVideoFileNameByDate(string baseOutpputPath, string extFile, int camercaId, DateTime dDate)
        {

            if (baseOutpputPath.Substring(baseOutpputPath.Length - 1, 1).Equals("\\"))
            {
                baseOutpputPath = baseOutpputPath.Substring(0, baseOutpputPath.Length - 1);
            }
            string startPath = string.Format("{0}\\{1}\\{2}{3}{4}\\{5}\\{6}.{7}",
                                baseOutpputPath,
                                camercaId,
                                dDate.Year.ToString("d4"),
                                dDate.Month.ToString("d2"),
                                dDate.Day.ToString("d2"),
                                dDate.Hour.ToString("d2"),
                                dDate.Minute.ToString("d2"),
                                extFile 
                                );


            return startPath;
        }

        public static string GenerateSavePath(string baseOutpputPath, int camercaId, DateTime dTime)
        {
            if (baseOutpputPath.Substring(baseOutpputPath.Length - 1, 1).Equals("\\"))
            {
                baseOutpputPath = baseOutpputPath.Substring(0, baseOutpputPath.Length - 1);
            }
            string path = string.Format("{0}\\{1}\\{2}{3}{4}\\{5}\\",
                                baseOutpputPath,
                                camercaId,
                                dTime.Year.ToString("d4"),
                                dTime.Month.ToString("d2"),
                                dTime.Day.ToString("d2"),
                                dTime.Hour.ToString("d2")
                                );
            if (!Directory.Exists(path))
                Directory.CreateDirectory(path);
            return path;
        }
        public static string GenerateSaveFilePath(string baseOutpputPath, string extFile, int camercaId, DateTime dTime)
        {
            if (baseOutpputPath.Substring(baseOutpputPath.Length - 1, 1).Equals("\\"))
            {
                baseOutpputPath = baseOutpputPath.Substring(0, baseOutpputPath.Length - 1);
            }
            string path = string.Format("{0}\\{1}\\{2}{3}{4}\\{5}\\",
                                baseOutpputPath,
                                camercaId,
                                dTime.Year.ToString("d4"),
                                dTime.Month.ToString("d2"),
                                dTime.Day.ToString("d2"),
                                dTime.Hour.ToString("d2")
                                );
            if (!Directory.Exists(path))
                Directory.CreateDirectory(path);
            path = path + string.Format("{0}.{1}", dTime.Minute.ToString("d2"), extFile);

            return path;
        }

        public static bool IsDate(string dateStr)
        {
            return System.Text.RegularExpressions.Regex.IsMatch(dateStr, @"^(19|20)\d\d(0[1-9]|1[012])(0[1-9]|[12][0-9]|3[01])$");

        }

        public static DateTime GetOldestDate(int cameraId)
        {
            var cameraRoot = Path.Combine(Config.VideoPath, cameraId.ToString());
            if (!Directory.Exists(cameraRoot)) return default(DateTime);

            var oldest = DateTime.MaxValue;
            var dirs = Directory.GetDirectories(cameraRoot);
            foreach (var dir in dirs)
            {
                var dirName = GetDirectoryName(dir);
                if (IsDate(dirName))
                {
                    var y = int.Parse(dirName.Substring(0, 4));
                    var m = int.Parse(dirName.Substring(4, 2));
                    var d = int.Parse(dirName.Substring(6, 2));
                    var dt = new DateTime(y, m, d);
                    if (dt < oldest)
                    {
                        oldest = dt;
                    }
                }
                
            }

            if (oldest != DateTime.MaxValue)
            {
                return oldest;
            }
            else
            {
                return default(DateTime);
            }

        }

        public static void DeleteOldestDate(int cameraId)
        {
            var oldest = GetOldestDate(cameraId);
            if (oldest != default(DateTime))
            {
                var path = DirectoryForDate(cameraId, oldest);
                if (Directory.Exists(path))
                {
                    Directory.Delete(path, true);
                }
            }

        }


        private static string DirectoryForDate(int cameraId, DateTime dt)
        {
            var relative = string.Format("{0}\\{1:d4}{2:d2}{3:d2}", cameraId, dt.Year, dt.Month, dt.Day);
            var path = Path.Combine(Config.VideoPath, relative);
            return path;
        }
        private static string GetDirectoryName(string path)
        {
            var idx = path.LastIndexOf(Path.DirectorySeparatorChar);
            return path.Substring(idx + 1);
        }
    }
}
